import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import utils from '../utils'

import { Modal } from 'view-design'

class HttpRequest {
  constructor () {
    this.baseUrl = process.env.VUE_APP_API_URL
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        token: localStorage.getItem('token')
      },
      responseType: 'blob'
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
  }

  /**
	 * 格式化传入的数据
	 */
  formatReqData (method, data) {
    const upperCaseMethod = method.toUpperCase()
    let k = ''
    let postData
    switch (upperCaseMethod) {
      case 'POST':
      case 'PUT':
      case 'DELETE':
        k = 'data'
        postData = qs.stringify(data)
        break
      case 'GET':
        k = 'params'
        postData = data
        break
      default:
        throw new Error('不认识的methods')
    }
    return {
      k,
      postData
    }
  }

  /**
	 * 回到登陆
	 */
  toLogin () {
    router.push({
      name: 'login'
    })
  }

  errorMsg (res) {
    Modal.error({
      title: '系统提示',
      content: res.msg
    })
  }

  /**
	 * 错误处理
	 */
  async errorCode (res) {
    switch (Number(res.code)) {
      case 1: // 正常数据
        return res
      case 401: // 未登录
        this.toLogin()
        break
      default:
        this.errorMsg(res)
        break
    }
  }

  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        this.queue[url] = true
        const { method, data } = config
        const { k, postData } = this.formatReqData(method, data)
        config[k] = postData
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        if (res.headers['content-type'] == 'application/json; charset=utf-8') {
          const { data } = res
          if (data.code !== 1) {
            this.errorCode(data)
            throw data
          }
          return data
        } else {
          return res
        }
      },
      error => {
        Modal.error({
          title: '系统提示',
          content: '系统错误，服务器异常'
        })
        return Promise.reject(error)
      }
    )
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
